package controller

import (
	"encoding/json"
	"gdfs-center/controller/vo"
	"gdfs-center/jwt"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
)

//jwt token校验中间件
func JWTAuth(c *gin.Context) {
	log.Println("###开始校验路径:", c.Request.URL.Path)
	if c.Request.URL.Path == "/gdfs/sys/login" {
		//登录无需校验token直接跳转
		log.Println("####登录无需校验token直接跳转")
		c.Next()
		return
	}
	//获取token

	token := c.Request.Header.Get("token")
	if token == "" {
		token = c.Query("token")
		if token == "" {
			WritedString(c.Writer, false, "-1", "token校验失败,无权限访问", nil)
			c.Abort() //终止
			return
		}
	}

	// parseToken 解析token包含的信息
	claims, err := jwt.ParseToken(token)
	if err != nil {
		if err == jwt.TokenExpired {
			WritedString(c.Writer, false, "-1", "授权已过期", nil)
			c.Abort()
			return
		}
		WritedString(c.Writer, false, "-1", "授权已过期", nil)
		c.Abort()
		return
	}
	log.Println("###token------------:", token, "###用户名:", claims.Username)
	c.Set("username", claims.Username)
	c.Next()
}

func WritedString(w http.ResponseWriter, sucess bool, code string, msg string, data interface{}) {
	result := vo.NewResultInstance()
	if sucess {
		result.Sucess(msg, code, data)
	} else {
		result.Fail(msg, code, data)
	}
	bytejson, _ := json.Marshal(result)
	io.WriteString(w, string(bytejson))
}
